import { Button, Card, Form, Input, List, Tag, message } from 'antd';
import { useState } from 'react'
import { RegexRule, ruleList } from './rules';
import { writeText } from '@tauri-apps/api/clipboard';


interface RuleItemProps {
  rule: RegexRule;
}

function RuleItem(props: RuleItemProps) {
  const [value, setValue] = useState("");

  return (
    <Card title={props.rule.title} style={{ width: "100%" }} headStyle={{ backgroundColor: "#eee" }} bordered={false}>
      <Form labelCol={{ span: 3 }}>
        <Form.Item label="正则">
          <span>{props.rule.rule.source}&nbsp;
            <Button type="link" onClick={e => {
              e.stopPropagation();
              e.preventDefault();
              writeText(props.rule.rule.source);
              message.info("复制成功");
            }}>复制</Button></span>
        </Form.Item>
        <Form.Item label="正面例子">
          {props.rule.examples.map(item => (
            <Tag>{item}</Tag>
          ))}
        </Form.Item>
        {props.rule.counterExamples !== undefined && (
          <Form.Item label="负面例子">
            {props.rule.counterExamples.map(item => (
              <Tag>{item}</Tag>
            ))}
          </Form.Item>
        )}
        <Form.Item label="测试" help={
          <>
            {props.rule.rule.test(value) && (
              <span style={{ color: "green" }}>命中规则</span>
            )}
            {!props.rule.rule.test(value) && value != "" && (
              <span style={{ color: "red" }}>未命中规则</span>
            )}
          </>
        }>
          <Input value={value} onChange={e => {
            e.stopPropagation();
            e.preventDefault();
            setValue(e.target.value);
          }} />
        </Form.Item>
      </Form>
    </Card>
  );
}

function App() {
  const [keyword, setKeyword] = useState("");

  return (
    <Card title="正则大全" extra={
      <Form>
        <Form.Item label="关键词">
          <Input allowClear value={keyword} onChange={e => {
            e.stopPropagation();
            e.preventDefault();
            setKeyword(e.target.value);
          }} />
        </Form.Item>
      </Form>
    }>
      <List rowKey="title" dataSource={ruleList.filter(rule => rule.title.includes(keyword))} pagination={false}
        renderItem={item => (
          <List.Item>
            <RuleItem rule={item} />
          </List.Item>
        )} />
    </Card>
  )
}

export default App
